﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Microsoft.Maps.MapControl;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace imaginecup
{
    public partial class pollutedMap : UserControl
    {
        private ServiceReference1.DataProviderSoapClient getPollutedUnitClient = new imaginecup.ServiceReference1.DataProviderSoapClient();
        List<ServiceReference1.CPollutedRecord> plist;
        private int addtype;
        private string uriprefix = "http://localhost:1276/photo/";

        public pollutedMap()
        {
            InitializeComponent();

            //添加事件处理
            getPollutedUnitClient.getPolluteUnitCompleted += new EventHandler<imaginecup.ServiceReference1.getPolluteUnitCompletedEventArgs>(getPollutedUnitClient_getPolluteUnitCompleted);
            getPollutedUnitClient.getPollutedRecordCompleted += new EventHandler<imaginecup.ServiceReference1.getPollutedRecordCompletedEventArgs>(getPollutedUnitClient_getPollutedRecordCompleted);
        }

        

        /// <summary>
        /// 数据下载完毕后的动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void getPollutedUnitClient_getPolluteUnitCompleted(object sender, imaginecup.ServiceReference1.getPolluteUnitCompletedEventArgs e)
        {
            List<ServiceReference1.CPollutedUnit> list = new List<ServiceReference1.CPollutedUnit>(e.Result);
            AddPollutedLayer(list);
            //testaddlayer();
        }

        private void testaddlayer()
        {
                        //Change the map mode to the base Mercator mode
            //testmap.Mode = new MercatorMode();
            testmap.SetView(new Location(47.606115, -122.324495), 15);

            //Add new MapLayer containing the shape 
            MapLayer newLayer = new MapLayer();
            MapPolygon poly = new MapPolygon();

            //Define the polygon vertices
            LocationCollection boundingLocations = new LocationCollection();
            boundingLocations.Add(new Location(47.605, -122.323));
            boundingLocations.Add(new Location(47.607, -122.323));
            boundingLocations.Add(new Location(47.606115, -122.325));

            //Set the polygon properties
            poly.Locations = boundingLocations;
            poly.Fill = new SolidColorBrush(Colors.Green);
            poly.Stroke = new SolidColorBrush(Colors.Blue);
            poly.StrokeThickness = 4;
            poly.Opacity = 0.1;
            newLayer.Children.Add(poly);

            //Add the layer containing the polygon to the map
            testmap.Children.Add(newLayer);
        }

        /// <summary>
        /// 为地图添加某种污染类型的图层
        /// 具体从哪一级数据库中取出数据由当前的level决定
        /// 至于每一级是否能够显示污染图层还有待考虑
        /// </summary>
        /// <param name="type"></param>
        public void AddPollutedLayer(int type)
        {
            getPollutedUnitClient.getPolluteUnitAsync(testmap.BoundingRectangle.East,
                            testmap.BoundingRectangle.West,
                            testmap.BoundingRectangle.North,
                            testmap.BoundingRectangle.South,
                            (int)testmap.ZoomLevel,
                            type);
            addtype = type;
        }

        /// <summary>
        /// 在获取数据后添加到图层
        /// </summary>
        /// <param name="list"></param>
        private void AddPollutedLayer(List<ServiceReference1.CPollutedUnit> list)
        {
            //int type = list[0].Type;
            int type = addtype;
            
            testmap.Children.Clear();
            //判断是否要观察污染程度图
            //若是，则删除图层(汉字部分是不知道如何实现)

            //*************Chagnge the map mode to the base Mercator mode********
            //myMap.Mode = new MercatorMode();
            //myMap.SetView(new Loacation(47.606115, -122.324495), 15);

            //**************Add new MapLayer containing the shape************
            //MapLayer newLayer = new MapLayer();
            MapLayer newLayer = new MapLayer();

            //1.读取type，rank
            //2.根据相应的type我们来得到相应等级的分块数目，和间距（type=0,dl=?,count=?）


            for (int i = 0; i < list.Count; i++)
            {
                ServiceReference1.CPollutedUnit elem = list[i];
                MapPolygon poly = new MapPolygon();
                LocationCollection boundingLocations = new LocationCollection();
                //tmptest
                double width = Public.getLevelLength((int)(testmap.ZoomLevel));
                
                //注意这里的节点的添加顺序就是画线的顺序
                boundingLocations.Add(new Location(elem.NorthLatitude, elem.WestLongtitude));
                boundingLocations.Add(new Location(elem.NorthLatitude + width, elem.WestLongtitude));
                boundingLocations.Add(new Location(elem.NorthLatitude+width, elem.WestLongtitude+width));
                boundingLocations.Add(new Location(elem.NorthLatitude, elem.WestLongtitude + width));

                poly.Locations = boundingLocations;
                //根据相应的level来定义颜色(rank=?(取值为0-1))
                //  相应颜色的定义:大气：（112 128 144）type==1，真实值（112*rank 128*rank 144*rank）
                //                 水：（160 32 240）type==2，真实值（160*rank 32*rank 240*rank）
                //                 噪声：（156 102 31）type==3，真实值（156*rank 102*rank 31*rank）
                //                 土壤：（94 38 18）type==4，真实值（94*rank 38*rank 18*rank）
                //                 综合：type==5，（112*rank+160*rank+156*rank+94*rank 128*rank+32*rank+102*rank+38*rank 144*rank+240*rank+31*rank+18*rank）
                Color c = new Color();
                switch (type)
                {
                    case 1:

                        c.R = (byte)((int)(112 * elem.Rank_1));
                        c.G = (byte)((int)(128 * elem.Rank_1));
                        c.B = (byte)((int)(144 * elem.Rank_1));
                        break;

                    case 2:

                        c.R = (byte)((int)(160 * elem.Rank_2));
                        c.G = (byte)((int)(32 * elem.Rank_2));
                        c.B = (byte)((int)(240 * elem.Rank_2));
                        break;

                    case 3:

                        c.R = (byte)((int)(156 * elem.Rank_3));
                        c.G = (byte)((int)(102 * elem.Rank_3));
                        c.B = (byte)((int)(31 * elem.Rank_3));
                        break;

                    case 4:

                        c.R = (byte)((int)(94 * elem.Rank_4));
                        c.G = (byte)((int)(38 * elem.Rank_4));
                        c.B = (byte)((int)(18 * elem.Rank_4));
                        break;

                    case 0:

                        c.R = (byte)((int)((112 * elem.Rank_1 + 160 * elem.Rank_2 + 156 * elem.Rank_3 + 94 * elem.Rank_4) / 4));
                        c.G = (byte)((int)(128 * elem.Rank_1 + 32 * elem.Rank_2 + 102 * elem.Rank_3 + 38 * elem.Rank_4)/4);
                        c.B = (byte)((int)((144 * elem.Rank_1 + 240 * elem.Rank_2 + 31 * elem.Rank_3 + 18 * elem.Rank_4)/4));                       
                        break;

                }
                

                //*********Set the polygon properties******
                poly.Locations = boundingLocations;
                c.A = 255;
                poly.Fill = new SolidColorBrush(c);
                poly.Opacity = 0.5;
                newLayer.Children.Add(poly);
            }

            //**********Add the layer containing the polygon to he map*******
            testmap.Children.Add(newLayer);
        }

        /// <summary>
        /// 添加标注点信息
        /// </summary>
        public void AddPointLayer()
        {
            getPollutedUnitClient.getPollutedRecordAsync(testmap.BoundingRectangle.East,
                                            testmap.BoundingRectangle.West,
                                            testmap.BoundingRectangle.North,
                                            testmap.BoundingRectangle.South);
        }

        /// <summary>
        /// 在获取标注点结束后添加标注点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void getPollutedUnitClient_getPollutedRecordCompleted(object sender, imaginecup.ServiceReference1.getPollutedRecordCompletedEventArgs e)
        {
            //这里还有一个bug，就是有一层pointlayer之后需要先移去此layer，然后再添加，否则会有异常

            plist = new List<ServiceReference1.CPollutedRecord>(e.Result);

            MapLayer layer = new MapLayer();
            layer.Name = "pointlayer";

            for (int i = 0; i < plist.Count; i++)
            {
                ServiceReference1.CPollutedRecord p = plist[i];
                
                Pushpin pp = new Pushpin();
                pp.Location = new Location(p.Latitude, p.Longtitude);
                pp.Content = p.Name;
                pp.Name = "p" + i;

                pp.MouseEnter += new MouseEventHandler(pp_MouseEnter);
                pp.MouseLeave += new MouseEventHandler(pp_MouseLeave);

                layer.Children.Add(pp);
            }

            testmap.Children.Add(layer);
        }

        void pp_MouseLeave(object sender, MouseEventArgs e)
        {
            //throw new Exception("未实现");
            //删除textlayer
            int i;
            for (i = 0; i < testmap.Children.Count; i++)
            {
                string str = testmap.Children[i].GetType().Name;
                MapLayer m = (MapLayer)(testmap.Children[i]);
                if (m.Name == "textlayer")
                {
                    break;
                }
            }
            testmap.Children.RemoveAt(i);
        }

        void pp_MouseEnter(object sender, MouseEventArgs e)
        {
            
            Pushpin p = (Pushpin)(sender);
            string str = p.Name;
            str = str.Substring(1, str.Length - 1);
            int index = Convert.ToInt32(str);

            MapLayer textlayer = new MapLayer();
            textlayer.Name = "textlayer";

            StackPanel sp = new StackPanel();
            sp.Orientation = Orientation.Vertical;
            sp.Opacity = 0.9;
            sp.Background = new SolidColorBrush(Colors.White);

            TextBlock tbname = new TextBlock();
            tbname.Text = "留言者："+plist[index].Name;
            sp.Children.Add(tbname);

            TextBlock tbtime = new TextBlock();
            tbtime.Text = "留言时间：" + plist[index].PostTime;
            sp.Children.Add(tbtime);

            TextBlock tbcomment = new TextBlock();
            tbcomment.Text = "留言内容：" + plist[index].Comments;
            sp.Children.Add(tbcomment);

            try
            {
                if (plist[index].Images != "")
                {
                    Uri fronturi = new Uri(uriprefix + plist[index].Images);
                    Image image = new Image();
                    image.Width = 200;
                    image.Height = 150;
                    BitmapImage imagesource = new BitmapImage(fronturi);
                    image.Source = imagesource;
                    sp.Children.Add(image);
                }
            }
            catch (Exception except)
            {
            }

            textlayer.AddChild(sp, new Location(plist[index].Latitude, plist[index].Longtitude));

            testmap.Children.Add(textlayer);
        }
    }
}
